import React from 'react';
import {
  FormPanel,
  FormPanelType,
  FormPanelBtnAlign,
  InputType,
  FormPanelObject,
  FormPanelBtnDisplay,
  FormPanelStatus,
} from 'lfun-bg-comp';
import { Button, Modal, Table, TableProps, Card, Steps } from 'antd';
import { useParams } from 'react-router-dom';
import dayjs from 'dayjs';
import { LogSearchParams, searchLogs } from '@/service/unit/logs';
import { PAGINATIONCONFIG } from '@/constant/page';
import { PageParams, getWorkFlowDefine, getWorkFlowSNodeLogs } from '@/service';
import { isPermissionOperate } from '@/component/permission-button';
import _ from 'lodash';
import { EVENT_NAMES } from '@/constant/basicOptions';
import { KG_ORDER_STATUS } from '@/constant/schoolOptions';

const list: FormPanelType[] = [
  {
    title: '',
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    inputs: [
      {
        label: '事件类型',
        name: 'change_module',
        key: 'change_module',
        inputType: InputType.select,
        renderOption: EVENT_NAMES,
      },
      // {
      //   label: '编号',
      //   name: 'process_instance_id',
      //   key: 'process_instance_id',
      // },
    ],
  },
];

const Groups: React.FC<{ operation_target_type: string }> = ({ operation_target_type }) => {
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [total, setTotal] = React.useState(0);
  const [form, setForm] = React.useState<FormPanelObject>();
  const [showModal, setShowModal] = React.useState(false);
  const [showView, setShowView] = React.useState(false);
  const [eventItems, setEventItems] = React.useState<any[]>([]);
  const [curLog, setCurLog] = React.useState<any>({});
  const { id } = useParams();
  const [curStepIndex, setCurStepIndex] = React.useState(0);

  const columns: TableProps['columns'] = [
    {
      title: '编号',
      dataIndex: 'process_instance_id',
      key: 'process_instance_id',
      width: 100,
      render: (text, record, index) => index + 1
    },
    {
      title: '事件类型',
      dataIndex: 'change_module',
      key: 'change_module',
      width: 100,
      render: (text) => {
        return _.find(EVENT_NAMES, { value: text })?.label;
      }
    },
    {
      title: '事件详情',
      dataIndex: 'change_detail',
      key: 'change_detail',
      width: 300,
      render: (text, record) => {
        if (text === '详情') {
          return (
            <Button
              type="link"
              onClick={() => {
                setCurLog(record);
                setShowModal(true);
              }}
            >
              {text}
            </Button>
          );
        }
        return text;
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: 150,
      hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Button
            type="link"
            onClick={async () => {
              const res = await getWorkFlowSNodeLogs(record.process_instance_id);
              const flows = await getWorkFlowDefine(record.process_instance_id);
              if (res.success && flows.success) {
                const logs = res.data?.reverse();
                setCurStepIndex(res.data.length - 1);
                setEventItems(
                  flows.data.map((it, idx) => {
                    return {
                      title: `${it.node_name}`,
                      description: getFlowDes(it, logs[idx]),
                    };
                  })
                );
              }
              setCurLog(record);
              setShowView(true);
            }}
          >
            查看
          </Button>
        );
      },
    },
  ];
  const getFlowDes = (item, log) => {
    return (
      <div>
        <div>
          {item.assign_role || '管理员'}
          {log ? `:${log.operator_name} ${dayjs(log.operation_time).format('YYYY年MM月DD日 HH:mm:ss')}` : ''}
        </div>
        {log &&
          (log.action === 'initiate' ? (
            ''
          ) : (
            <div>
              {log.action === 'approved' && <span>审核通过</span>}
              {log.action === 'rejected' && <span style={{ color: 'red' }}>审核拒绝</span>}
              {log.action === 'revoke' && <span>撤回</span>}
            </div>
          ))}
        {log &&
          (log.action === 'initiate' ? (
            <div>说明: {log.description || '-'}</div>
          ) : log.action.indexOf('_end') !== -1 ? (
            ''
          ) : (
            <div>审核说明: {log.description || '-'}</div>
          ))}
      </div>
    );
  };
  const searchFun = async (pageIndex, pageSize) => {
    setLoading(true);
    const params: LogSearchParams & PageParams = {
      operation_target_type, //'school',
      action_target_id: id,
      ...(form ? form.getFieldsValue() : {}),
      page: pageIndex,
      per_page: pageSize,
    };
    const res = await searchLogs(params);
    if (res.success) {
      setDataSource(res.data.items);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
      setTotal(res.data.total);
    }
    setLoading(false);
  };
  React.useEffect(() => {
    searchFun(pageIndex, pageSize);
  }, []);
  // const buildBtns = () => {
  //   return [<Button onClick={() => true}>导出</Button>];
  // };
  const pageChange = (page: number, size: number) => {
    searchFun(page, size);
  };
  const getDataSource = () => {
    try {
      if (curLog.change_data) {
        const arr = [];
        const change_data = JSON.parse(decodeURIComponent(curLog.change_data));
        for (const key in change_data) {
          arr.push({
            module: curLog.change_module,
            key,
            before: change_data[key].before,
            after: change_data[key].after,
          });
        }
        return arr;
      }
    } catch (ex) {
      return [];
    }
    return [];
  };
  return (
    <>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        template={list}
        //buttons={buildBtns()}
        submitBtnText="查询"
        onReset={() => {
          searchFun(1, pageSize);
          return true;
        }}
        onFinish={() => {
          searchFun(1, pageSize);
        }}
        onLoad={(formPanelObject: FormPanelObject) => {
          setForm(formPanelObject);
          return true;
        }}
      />
      <Table
        dataSource={dataSource}
        columns={columns}
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Modal title="变更记录" width="60%" open={showModal} footer={null} onCancel={() => setShowModal(false)}>
        <Table
          dataSource={getDataSource()}
          columns={[
            {
              title: '变更模块',
              dataIndex: 'module',
              key: 'module',
              render: (text) => {
                return _.find(EVENT_NAMES, { value: text })?.label;
              }
            },
            {
              title: '变更字段',
              dataIndex: 'key',
              key: 'key',
            },
            {
              title: '变更前',
              dataIndex: 'before',
              key: 'before',
              render: (text) => {
                return _.find(KG_ORDER_STATUS, { value: text })?.label;
              }
            },
            {
              title: '变更后',
              dataIndex: 'after',
              key: 'after',
              render: (text) => {
                return _.find(KG_ORDER_STATUS, { value: text })?.label;
              }
            },
          ]}
        />
      </Modal>
      <Modal title={curLog.change_detail} width="60%" open={showView} footer={null} onCancel={() => setShowView(false)}>
        <FormPanel
          buttonsDisplay={FormPanelBtnDisplay.none}
          formStatus={FormPanelStatus.nonEdit}
          values={curLog}
          template={[
            {
              labelCol: { span: 8 },
              wrapperCol: { span: 16 },
              inputs: [
                {
                  label: '变更ID',
                  name: 'process_instance_id',
                  key: 'process_instance_id',
                },
                {
                  label: '事件类型',
                  name: 'change_module',
                  key: 'change_module',
                  inputType: InputType.select,
                  renderOption: EVENT_NAMES,
                },
              ],
            },
          ]}
        />
        {curLog.change_data && curLog.change_data.length && curLog.change_data.length > 0 ? (
          <Card title="事件详情">
            <Table
              dataSource={getDataSource()}
              columns={[
                {
                  title: '变更模块',
                  dataIndex: 'module',
                  key: 'module',
                  render: (text) => {
                    return _.find(EVENT_NAMES, { value: text })?.label;
                  }
                },
                {
                  title: '变更字段',
                  dataIndex: 'key',
                  key: 'key',
                },
                {
                  title: '变更前',
                  dataIndex: 'before',
                  key: 'before',
                },
                {
                  title: '变更后',
                  dataIndex: 'after',
                  key: 'after',
                },
              ]}
            />
          </Card>
        ) : (
          <Card title="事件详情">{curLog.change_detail}</Card>
        )}
        <Card title="审核流程">
          {eventItems && eventItems.length > 0 ? (
            <Steps direction="vertical" size="small" current={curStepIndex} items={eventItems} />
          ) : (
            '无'
          )}
        </Card>
      </Modal>
    </>
  );
};

export default Groups;
